<template>
  <a-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    :wrapClassName="wrapClassNameInfo()"
    @ok="handleSubmit"
    @cancel="close"
    cancelText="关闭(ESC)"
    style="top:5%;height: 90%;overflow-y: hidden"
  >
    <a-row :gutter="10" style="padding: 10px; margin: -10px">
      <a-col :md="24" :sm="24">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="onSearch">
            <a-row :gutter="24">
              <a-col :md="6" :sm="8">
                <a-form-item label="医嘱项目" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                  <a-input ref="material" placeholder="医嘱项目" v-model="queryParam.projectName"></a-input>
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :md="6" :sm="24">
                  <a-button type="primary" @click="loadMaterialData(1)">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset(1)">重置</a-button>
                </a-col>
              </span>
            </a-row>
          </a-form>
          <a-table
            ref="table"
            :scroll="scrollTrigger"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"
            :loading="loading"
            :customRow="rowAction"
            @change="handleTableChange">
          </a-table>
        </div>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
import { getAction, getFileAccessHttpUrl } from '@/api/manage'
import {filterObj} from '@/utils/util'
import {getProjectBySelect} from '@/api/api'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import {mixinDevice} from '@/utils/mixin'
import Vue from 'vue'

export default {
  name: 'JSelectSnModal',
  mixins:[JeecgListMixin, mixinDevice],
  components: {

  },
  props: ['rows', 'multi', 'barCode'],
  data() {
    return {
      modalWidth: 1450,
      queryParam: {
        projectName: '',
        medicineType:'',
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      categoryTree:[],
      columns: [
        {dataIndex: 'projectName', title: '项目名称'},
        {dataIndex: 'price', title: '单价'},
        {dataIndex: 'discription', title: '描述'}
      ],
      scrollTrigger: {},
      dataSource: [],
      selectedRowKeys: [],
      selectMaterialRows: [],
      selectMaterialIds: [],
      title: '选择项目',
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter: {
        column: 'id',
        order: 'desc'
      },
      visible: false,
      form: this.$form.createForm(this),
      loading: false,
      expandedKeys: [],
      disableMixinCreated: true,
    }
  },
  computed: {
    // 计算属性的 getter
    getType: function () {
      return this.multi == true ? 'checkbox' : 'radio';
    }
  },
  watch: {
    barCode: {
      immediate: true,
      handler() {
        this.initBarCode()
      }
    },
  },
  created() {
    // 该方法触发屏幕自适应
    this.resetScreenSize()
  },
  methods: {
    initBarCode() {
      if (this.barCode) {
        this.$emit('initComp', this.barCode)
      } else {
        // JSelectUserByDep组件bug issues/I16634
        this.$emit('initComp', '')
      }
    },
    loadMaterialData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      this.loading = true
      let params = this.getQueryParams()//查询条件
      getAction("/his/care/project/list").then((res) => {
        if (res) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
          if(res.result.total===1) {
            if(this.queryParam.projectName === this.dataSource[0].projectName) {
              this.title = '选择医嘱项目【再次回车可以直接选中】'
              this.$nextTick(() => this.$refs.material.focus());
            } else {
              this.title = '选择医嘱项目'
            }
          } else {
            this.title = '选择医嘱项目'
          }
        }
      }).finally(() => {
        this.loading = false
      })
    },
    // 触发屏幕自适应
    resetScreenSize() {
      let realScreenWidth = window.screen.width
      this.modalWidth = realScreenWidth<1600?'1200px':'1450px'
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.scrollTrigger = {x: 800};
      } else {
        this.scrollTrigger = {};
      }
    },
    showModal(barCode) {
      this.visible = true;
      this.title = '选择项目'
      this.queryParam.projectName = barCode
      this.$nextTick(() => this.$refs.material.focus());
      this.loadMaterialData();
      this.form.resetFields();
    },
    getQueryParams() {
      let param = Object.assign({}, this.queryParam, this.isorter);
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      return filterObj(param);
    },
    getQueryField() {
      let str = 'id,';
      for (let a = 0; a < this.columns.length; a++) {
        str += ',' + this.columns[a].dataIndex;
      }
      return str;
    },
    searchReset(num) {
      let that = this;
      if (num !== 0) {
        that.queryParam = {};
        that.loadMaterialData(1);
      }
      that.selectedRowKeys = [];
      that.selectMaterialIds = [];
    },
    close() {
      this.searchReset(0);
      this.visible = false;
    },
    handleTableChange(pagination, filters, sorter) {
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc';
      }
      this.ipagination = pagination;
      this.loadMaterialData();
    },
    handleSubmit() {
      let that = this;
      this.getSelectMaterialRows();
      that.$emit('ok', that.selectMaterialRows, that.selectMaterialIds);
      that.searchReset(0)
      that.close();
    },
    //获取选择信息
    getSelectMaterialRows(rowId) {
      let dataSource = this.dataSource;
      let materialIds = "";
      this.selectMaterialRows = [];
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedRowKeys.includes(dataSource[i].id)) {
          this.selectMaterialRows.push(dataSource[i]);
          materialIds = materialIds + "," + dataSource[i].projectNo
        }
      }
      this.selectMaterialIds = materialIds.substring(1);
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    onSearch() {
      if(this.dataSource && this.dataSource.length===1) {
        if(this.queryParam.projectName === this.dataSource[0].projectName) {
          let arr = []
          arr.push(this.dataSource[0].projectNo)
          this.selectedRowKeys = arr
          this.handleSubmit()
        } else {
          this.loadMaterialData(1)
        }
      } else {
        this.loadMaterialData(1)
      }
    },
    modalFormOk() {
      this.loadMaterialData()
    },
    rowAction(record, index) {
      return {
        on: {
          click: () => {
            let arr = []
            arr.push(record.projectNo)
            this.selectedRowKeys = arr
          },
          dblclick: () => {
            let arr = []
            arr.push(record.projectNo)
            this.selectedRowKeys = arr
            this.handleSubmit()
          }
        }
      }
    }
  }
}
</script>

<style scoped>
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

#components-layout-demo-custom-trigger .trigger {
  font-size: 18px;
  line-height: 64px;
  padding: 0 24px;
  cursor: pointer;
  transition: color .3s;
}
</style>